package com.cheems.springbootinit.controller;

import cn.hutool.json.JSONObject;
import com.cheems.springbootinit.common.BaseResponse;
import com.cheems.springbootinit.common.ResultUtils;
import com.cheems.springbootinit.manager.AIManager;
import com.cheems.springbootinit.model.dto.AI.AIPlanRequest;
import com.cheems.springbootinit.model.dto.AI.AIRequest;
import com.cheems.springbootinit.model.entity.Course;
import com.cheems.springbootinit.model.vo.AIResponse;
import com.cheems.springbootinit.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/AI")
@Slf4j
public class AiController {

    @Resource
    private AIManager aiManager;
    
    @Resource
    private CourseService courseService;

    @PostMapping
    public BaseResponse<AIResponse> getAI(@RequestBody AIRequest aiRequest){
        String message = aiManager.sendMsgToXingHuoAI(false, aiRequest.getMessage());
        log.info("AI: " + message);
        AIResponse aiResponse = new AIResponse();
        aiResponse.setAIMessage(message);
        return ResultUtils.success(aiResponse);
    }

    @PostMapping("/plan")
    public BaseResponse<String> getStudyPlan(@RequestBody AIPlanRequest planRequest) {
        // 获取所有课程信息
        List<Course> courseList = courseService.list();
        
        // 构建课程信息字符串
        StringBuilder courseInfo = new StringBuilder("可选课程信息：\n");
        for (Course course : courseList) {
            courseInfo.append(String.format("- 课程ID：%d，课程名称：%s，课程图片：%s，课程描述：%s\n",
                course.getId(),
                course.getTitle(),
                course.getImage(),
                course.getDescription()));
        }
        
        // 构建发送给 AI 的提示信息
        String prompt = String.format(
            "请为一位学生制定学习计划，并以JSON格式返回。\n" +
            "学生信息：\n" +
            "- 当前水平：%s\n" +
            "- 学习目标：%s\n" +
            "- 每周可投入时间：%s\n" +
            "- 额外说明：%s\n\n" +
            "%s\n" +
            "请严格按照以下JSON格式返回数据：\n" +
            "{\n" +
            "  \"overview\": \"总体学习计划概述\",\n" +
            "  \"totalDuration\": 预计总学习时长(小时),\n" +
            "  \"recommendedCourses\": [\n" +
            "    {\n" +
            "      \"courseId\": 课程ID,\n" +
            "      \"courseName\": \"课程名称\",\n" +
            "      \"courseImage\": \"课程图片URL\",\n" +
            "      \"suggestedDuration\": 建议学习时长(小时),\n" +
            "      \"keyPoints\": [\"重点1\", \"重点2\"],\n" +
            "      \"learningOrder\": 学习顺序号\n" +
            "    }\n" +
            "  ],\n" +
            "  \"recommendations\": \"学习建议和注意事项\"\n" +
            "}",
            planRequest.getCurrentLevel(),
            planRequest.getTargetGoal(),
            planRequest.getAvailableTime(),
            planRequest.getAdditionalInfo(),
            courseInfo.toString()
        );
        
        // 调用 AI 服务获取响应
        String aiResponse = aiManager.sendMsgToXingHuoAI(false, prompt);
        log.info("AI Learning Plan Generated: " + aiResponse);
        
        // 清理 AI 响应，只保留 JSON 数据
        String cleanedResponse = cleanAIResponse(aiResponse);
        
        return ResultUtils.success(cleanedResponse);
    }

    /**
     * 清理 AI 响应，只保留 JSON 数据
     * @param aiResponse AI 原始响应
     * @return 清理后的 JSON 字符串
     */
    private String cleanAIResponse(String aiResponse) {
        // 1. 去除可能的 markdown 代码块标记
        String cleaned = aiResponse.replaceAll("```json\\s*", "")
                                 .replaceAll("```\\s*$", "");
        
        // 2. 查找第一个 { 和最后一个 } 的位置
        int startIndex = cleaned.indexOf("{");
        int endIndex = cleaned.lastIndexOf("}");
        
        // 3. 如果找到了完整的 JSON 结构，提取出来
        if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
            cleaned = cleaned.substring(startIndex, endIndex + 1);
        }
        
        // 4. 去除首尾空白字符
        cleaned = cleaned.trim();
        
        // 5. 验证是否是有效的 JSON 格式（可选）
        try {
            new JSONObject(cleaned);
            return cleaned;
        } catch (Exception e) {
            log.error("清理后的响应不是有效的 JSON 格式: " + cleaned, e);
            throw new RuntimeException("AI 返回的数据格式无效");
        }
    }
}
